import axios from "axios";
import store from "../store";
import router from "../router";
import {
	refreshToken
} from '/src//api/login.js';
import {
	Toast
} from 'vant';

// 创建axios实例
const service = axios.create({
	baseURL: process.env.VUE_APP_BASE_URL, // api 的 VUE_APP_URL
	crossDomain: true,
	withCredentials: false,
	timeout: 20000 // 请求超时时间
});
// request拦截器,在请求之前做一些处理
service.interceptors.request.use(
	config => {
		// 给请求头添加请求字段
		config.headers = {
			"Authorization": store.state.token,
			'Content-Type': 'multipart/form-data'
		}
		return config;
	},
	error => {
		console.log(error);
		Promise.reject(error);
	}
);
// 将请求数据转换成功 formdata 接收格式
service.defaults.transformRequest = (data) => {
	console.log('transformRequest', data);
	return stringify(data)
}

// response 拦截器,数据返回后进行一些处理
service.interceptors.response.use(
	response => {
		console.log('response', response.data);
		let disstr = response.data.code.toString();
		let newcode = parseInt(disstr.substring(0, 3));
		if (response.data.code == 401 || newcode == 401) {
			//刷新token
			refreshToken(store.state.refToken).then(
				res => {
					if (res.code == 200) {
						store.commit('updateToken', res.data.token);
						store.commit('updateRefToken', res.data.refreshToken);
						Toast("页面停留过长，请重试");
					} else {
						//token失效
						Toast(response.data.message);
						store.commit('clearnToken');
						//清除数据,跳转到登录界面
						localStorage.clear();
						router.push("/login");
					}
				},
				err => {
					//token失效
					Toast(response.data.message);
					store.commit('clearnToken');
					//清除数据,跳转到登录界面
					localStorage.clear();
					router.push("/login");
				}
			);
			return response.data;
		} else if (response.data.code == 200) {
			//请求数据成功
			return response.data;
		} else { //其他异常情况
			if (response.data.message) {
				Toast(response.data.message);
			}
			return response.data;
		}
	},
	error => {
		console.log('error', error);
		Toast('网络异常，请重试');
		return Promise.reject(error);
	}
);

// 将参数转换成功 formdata 接收格式
function stringify(data) {
	const formData = new FormData()
	for (const key in data) {
		// eslint-disable-next-line no-prototype-builtins
		if (data.hasOwnProperty(key)) {
			if (data[key]) {
				if (data[key].constructor === Array) {
					if (data[key][0]) {
						if (data[key][0].constructor === Object) {
							formData.append(key, JSON.stringify(data[key]))
						} else {
							data[key].forEach((item, index) => {
								formData.append(key + `[${index}]`, item)
							})
						}
					} else {
						formData.append(key + '[]', '')
					}
				} else if (data[key].constructor === Object) {
					formData.append(key, JSON.stringify(data[key]))
				} else {
					formData.append(key, data[key])
				}
			} else {
				if (data[key] === 0) {
					formData.append(key, 0)
				} else {
					formData.append(key, '')
				}
			}
		}
	}
	return formData
}
export default service;
